<?php

/**
 * @author 陈韵
 * 广州魁星创建订单
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\Shopgzkx\ShopgzkxApiClient;

class Shopgzkx extends BaseSupplierRouterService
{
    /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //生成供应商主单号
        $supplierGoodsInfo      = $param['supplierGoodsInfo'];
        $supplierCode           = $supplierGoodsInfo['supplierCode'];
        $apiBody                = $supplierGoodsInfo['apiBody'];
        $thirdPartyPlatformCode = $supplierGoodsInfo['thirdPartyPlatformCode'];
        //下单商品组
        $userGoodsList          = $supplierGoodsInfo['userGoodsList'];
        //下单商品
        $orderGoods = [];
        foreach ($userGoodsList as $item ) {
            $orderGoods = array_merge($orderGoods,$item);
            unset($item);
        }
        
        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;
    
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;
        
        //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
        if( $isDelare && !$isShop ) {
            $param['order']['supplier_dsn'] = (string)$param['order']['orderSn'];
        } else {
            $param['order']['supplier_dsn'] = (string)(IdService::instance()->getOtherID());
        }
        $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
        $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
        $param['order']['goods'] = $orderGoods;
        $param['order']['isQueryExpress'] = 1;//查询物流单
        $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $orderItems[] = $res['data'];
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }
    
    /**
     * 订单申报
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        return $this->callSdkApi(ShopgzkxApiClient::class,$param['apiBody'])->createOrder($param);
    }

    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return $this->callSdkApi(ShopgzkxApiClient::class,$param['apiBody'])->cancelOrder($param);
    }
    
    /**
     * 获取物流信息
     * @param array $param
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $apiBody   = $param['apiBody'];
        $orderID   = $queryBody['orderID'];

        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }
        $order_id = $orderInfo['id'];
        //发起查询请求
        $res = $this->callSdkApi(ShopgzkxApiClient::class,$param['apiBody'])->orderExpress($orderInfo);
        
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        if( empty($res["data"]['Items']) ) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }
        //业务逻辑处理
        $Result = current($res['data']['Items']);
        
        //订单状态
        $OrderStatus = $Result['OrderDeclare'];
        $order_map = [
            '0'    => '失败',
            '2'    => '申报中',
            '3'    => '未申报',
            '4'    => '未知'
        ];
        
        if( isset($order_map[$OrderStatus]) ) {
            OrderSupplier::instance()->where('id',$order_id)->update([
                'order_push_remark' => "上游供应商订单状态为【{$order_map[$OrderStatus]}】",
            ]);
            return Normal::returnCode(Normal::FAIL,"上游供应商订单正在处理中");
        }
        //支付单状态
        $PayDeclareStatus = $Result['PayDeclare'];
        $payDeclare_map = [
            '0'    => '失败',
            '2'    => '申报中',
            '3'    => '未申报',
            '4'    => '未知',
            '6'    => '已撤销',
        ];
        if(isset($payDeclare_map[$PayDeclareStatus]) ) {
            OrderSupplier::instance()->where('id',$order_id)->update([
                'order_push_remark' => "上游供应商支付单状态为【{$payDeclare_map[$PayDeclareStatus]}】",
            ]);
            return Normal::returnCode(Normal::FAIL,"上游供应商订单正在处理中");
        }
        //清单状态
        $ClearanceDeclareStatus=$Result['ClearanceDeclare'];
        $ClearanceDeclare_map = [
            '0'    => '失败',
            '2'    => '申报中',
            '3'    => '未申报',
            '4'    => '未知',
            '6'    => '已撤销',
        ];
        if(isset($ClearanceDeclare_map[$ClearanceDeclareStatus]) ) {
            OrderSupplier::instance()->where('id',$order_id)->update([
                'order_push_remark' => "上游供应商清单状态为【{$ClearanceDeclare_map[$ClearanceDeclareStatus]}】",
            ]);
            return Normal::returnCode(Normal::FAIL,"上游供应商订单正在处理中");
        }
        
        if( empty($Result['TrackingNo']) ) {
            OrderSupplier::instance()->where('id',$order_id)->update([
                'order_push_remark' => "上游供应商物流运单号未出，请耐心等候",
            ]);
            return Normal::returnCode(Normal::FAIL,"上游供应商订单正在处理中");
        }
        
        if( empty($Result['ExpressCoName']) ) {
            OrderSupplier::instance()->where('id',$order_id)->update([
                'order_push_remark' => "上游供应商物流公司未出,请耐心等候",
            ]);
            return Normal::returnCode(Normal::FAIL,"上游供应商订单正在处理中");
        }
        
        $ExpressName = $Result['ExpressCoName'];
        $TrackingNo  = $Result['TrackingNo'];
        
        OrderSupplier::instance()->where('id',$order_id)->update([
            'order_push_remark' => "推送成功",
        ]);
        
        return  Normal::returnCode(Normal::SUC,"已发货",[
            'expressInfo' => [
                'express_name'  => mb_strtoupper($ExpressName,'utf-8'),
                'express_sn'    => $TrackingNo,
            ]
        ]);
    }

    /**
     * 商品列表查询接口
     * @param array $param
     * @return mixed
     */
    public function queryGoodsList( $param = [] )
    {
        $res = $this->callSdkApi(ShopgzkxApiClient::class,$param['apiBody'])->queryGoodsList($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total'     => count($res) ?? 0,
            'list'      => $res['data'],
            'hasPage'   => false//是否支持分页功能
        ]);
    }
}